#define _CRT_SECURE_NO_WARNINGS 1

class Solution {
public:
    bool use[101][101];
    int dx[4] = { 0, 0, 1, -1 };
    int dy[4] = { 1, -1, 0, 0 };

    bool exist(vector<string>& board, string word) {
        int range = board.size();
        for (int i = 0; i < range; i++)
        {
            for (int j = 0; j < board[i].size(); j++)
            {
                if (board[i][j] == word[0])
                    if (dfs(board, word, i, j, 0))
                        return true;
            }
        }
        return false;
    }
    bool dfs(vector<string>& borad, string& word, int x, int y, int pos)
    {
        if (pos == word.size() - 1) return true;
        use[x][y] = true;
        for (int k = 0; k < 4; k++)
        {
            int a = x + dx[k], b = y + dy[k];
            if (a >= 0 && b >= 0 && a < borad.size() && b < borad[x].size() && borad[a][b] == word[pos + 1] && use[a][b] == false)
                if (dfs(borad, word, a, b, pos + 1)) return true;
        }
        use[x][y] = false;
        return false;
    }
};